package com.jerry.netty.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Channel03 {
    public static void main(String[] args) throws Exception {
        //创建文件输入流和输入流通道
        FileInputStream fileInputStream = new FileInputStream("file_source.txt");
        FileChannel inputChannel = fileInputStream.getChannel();

        //创建文件输出流和输出流通道
        FileOutputStream fileOutputStream = new FileOutputStream("file_target.txt");
        FileChannel outputChannel = fileOutputStream.getChannel();

        //创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        //循环读取文件的内容
        while (true) {
            //特别重要的操作，一定不能忘记
            byteBuffer.clear();   //清空byteBuffer

            //将输入通道中的数据读取出来，放到缓冲区中
            int read = inputChannel.read(byteBuffer);
            System.out.println("read=="+read);
            if (read == -1) {  // -1代表已读完
                break;
            }

            //对 byteBuffer 进行 flip
            byteBuffer.flip();

            //将buffer中的数据写入到outputChannel
            outputChannel.write(byteBuffer);
        }

        //关闭流
        fileInputStream.close();
        fileOutputStream.close();
    }
}
